/**
 * @name zhangyy-g@grandsoft.com.cn
 * @description zhangyy's code
 * Date: 15-4-17
 * Time: 下午5:52
 *
 */
(function ($) {
    var layout = {
        __container: null,

        __filter: '',
        __path: '',

        __options: null,

        __headerPanel: null,
        __searchPanel: null,
        __filterPanel: null,
        __listPanel: null,

        init: function (container, options) {
            var self = this
            self.__container = container
            self.__options = options

            container.html(layoutTpl)

            self.__headerPanel = container.find('.header-wrap')
            self.__searchPanel = container.find('.search-wrap')
            self.__filterPanel = container.find('.doc-filter-wrap')
            self.__listPanel = container.find('.doc-list-wrap')

            $.jps.publish('dock-init', {
                listPanel: self.__listPanel
            })
            self.__initHeader(options)

            self.__bindEvent()
        },

        __initHeader: function (options) {
            var self = this
            var model = self.headerModel = new Backbone.Model(options)
            var view = new headerView({
                model: model
            })
            view.render().$el.appendTo(self.__headerPanel)
        },

        __bindEvent: function () {
            var self = this
            var container = self.__container
            var options = self.__options

            /*container.find('.search-input').focus(function () {
                container.removeClass('show-opt')
            }).blur(function () {
                var filter = self.__filter
                if (filter !== 'search') {
                    self.updateOpt({
                        filter: filter
                    })
                }
            })*/
            //搜索
            container.on('keyup', '.search-input', function () {
                var key = $.trim($(this).val())
                if (!key) {
                    var filter = self.__filter
                    if (filter !== 'search') {
                        self.updateOpt({
                            filter: filter
                        })
                    }
                }else{
                    container.removeClass('show-opt')
                    $.jps.publish('file-search', {
                        key: key,
                        path: self.__path
                    })

                    self.__filter = 'search'
                }
            })

            //查看
            container.on('click', '.filter-item', function () {
                var filter = $(this).data('filter')

                self.__filter = filter

                self.hideFilterPanel()

                $.jps.publish('file-list', {
                    filter: filter
                })
            })

            //点击opt item
            container.on('click', '.opt-item', function () {
                var action = $(this).data('action')
                if($(this).hasClass('disabled')) return false

                $.jps.publish('action-click', {
                    action: action,
                    filter: self.__filter,
                    path: self.__path
                })
            })
        },

        showFilterPanel: function () {
            this.__filterPanel.show()
            this.__listPanel.hide()
            this.clearSearch()
        },
        hideFilterPanel: function () {
            this.__filterPanel.hide()
            this.__listPanel.show()
        },

        updateHeader: function (options) {
            var self = this
            self.__path = options.path
            self.__filter = options.filter
            self.headerModel.set(options)
        },

        updateOpt: function (options) {
            var self = this
            var container = self.__container
            var filter = options.filter
            if (!filter || filter == 'favorite' || filter == 'myshare' || filter == 'search') {
                self.__container.removeClass('show-opt')
            } else {
                self.__container.addClass('show-opt')
            }

            if(filter == 'company') {
                container.find('.action-share').addClass('disabled')
            }else{
                container.find('.action-share').removeClass('disabled')
            }

            if(filter == 'share') {
                container.find('.action-shareto').addClass('disabled')
                if(options.path == App.common.modules.util.filterInfo('share').path) {
                    container.find('.action-newfolder').addClass('disabled')
                }else{
                    container.find('.action-newfolder').removeClass('disabled')
                }
            }else{
                container.find('.action-shareto').removeClass('disabled')
            }
        },

        clearSearch: function () {
            this.__container.find('.search-input').val('')
        }
    }

    var headerView = Backbone.View.extend({
        className: 'mod-header',
        events: {
            'click .back': 'back',
            'click .upload': 'uploadHandler'
        },
        initialize: function () {
            var self = this
            self.listenTo(self.model, 'change', self.render)
        },
        render: function () {
            var self = this
            var data = self.model.toJSON()
            var filter = data.filter
            self.model.set('gzq', false, {
                silent: true
            })
            if (!filter) {
                data.backName = '工作圈'
                data.title = '企业网盘'
                data.gzq = true
                data.upload = false
                self.model.set('gzq', true, {
                    silent: true
                })
            } else {
                if (filter == 'search') {
                    data.backName = '企业网盘'
                    data.title = '搜索'
                    data.path = ''
                    data.upload = false
                } else {
                    var filterInfo = App.common.modules.util.filterInfo(filter)
                    if (data.path == filterInfo.path) {
                        data.backName = '企业网盘'
                        data.title = filterInfo.name
                        data.path = ''
                    } else {
                        var pathArr = data.path.split('/').slice(0, -2)
                        var path = pathArr.join('/') + '/'
                        if (_.contains(App.common.modules.util.filterPath, path)) {
                            data.backName = filterInfo.name
                            data.title = data.fileName
                            data.path = 'filter'
                            self.model.set('backFilter', filter, {
                                silent: true
                            })
                        } else {
                            data.backName = pathArr[pathArr.length - 1]
                            data.title = data.fileName
                            data.path = path
                        }

                    }

                    data.upload = App.common.modules.util.canUpload(data)

                    if (filter == 'myshare' || filter == 'favorite') {
                        if (!data.path || data.path == '/') {
                            data.upload = false
                        }
                    }
                }
            }

            self.$el.html(Mustache.render(headerTpl, data))
            self.model.set('backPath', data.path, {
                silent: true
            })
            return self
        },
        //回退
        back: function (evt) {
            var self = this
            var model = self.model

            var gzq = model.get('gzq')

            if (gzq) {
                cordova.exec($.noop, $.noop, 'Destroy', 'destroy', [])
                return false
            }

            var backPath = model.get('backPath')

            if (!backPath) {
                //没有path就是切换
                $.jps.publish('filter-show')
            } else if (backPath == 'filter') {
                //进入到第一层的filter
                $.jps.publish('file-list', {
                    filter: self.model.get('backFilter')
                })
            } else {
                $.jps.publish('file-list', {
                    path: backPath,
                    filter: self.model.get('backFilter')
                })
            }
        },

        uploadHandler: function () {
            var self = this
            cordova.exec(function (fileData) {
                fileData = JSON.parse(fileData)
                //alert('本地选中了：' + JSON.stringify(fileData))
                var uploadUrl = App.common.modules.util.rootPath + '/review/file/cjtupload/'
                //alert('上传URL:' + uploadUrl)
                //alert('上传远程目录（remoteFilePath）：' + self.model.get('path'))
                if (fileData.code == 0) {
                    var files = fileData.data || []
                    for(var i = 0, len =files.length; i< len;i ++){
                        var file = files[i]
                        //alert('文件路径：' + file.path)
                        //alert('文件大小：' + file.size)
                        //alert('cookies信息：' + document.cookie)
                        cordova.exec(
                            function (data) {
                                //alert('成功:' + JSON.stringify(data))
                                $.jps.publish('file-list', {
                                    filter: self.model.get('filter'),
                                    path: self.model.get('path')
                                })
                            },
                            function (error) {
                                alert('上传失败：' + error)
                            },
                            'Upload', 'uploadFile',
                            [{
                                remote: uploadUrl,
                                fileDataKey: 'gzqtbpupload',
                                path: file.path,
                                size: file.size,
                                cookieInfo: document.cookie,
                                remoteFilePath: self.model.get('path')
                            }]
                        )
                    }
                } else {
                    App.common.modules.smallnote('选择文件错误，请重新选择', {
                        pattern: 'error'
                    })
                }
                return true
            }, function (error) {
                alert('打开失败')
            }, 'FileManager', 'open', []);
        }
    })

    var headerTpl = '' +
        '<a class="back" data-path="{{path}}"><span class="bf">&lt;</span>&nbsp;{{backName}}</a>' +
        '<div class="title">{{title}}</div>' +
        '{{#upload}}<div class="upload">上传</div>{{/upload}}'


    var layoutTpl = '' +
        '<div class="layout">' +
        '   <div class="header-wrap"></div>' +
        '   <div class="search-wrap">' +
        '       <img class="icon-search" src="/webstatic/filebox/css/images/search.png"/>' +
        '       <input name="search" class="search-input" />' +
        '   </div>' +
        '   <div class="doc-filter-wrap">' +
        '      <div class="filter-item" data-filter="myfile"><img class="icon-filter" src="/webstatic/filebox/css/images/personal.png" />我的文件</div>' +
        '      <div class="filter-item" data-filter="share"><img class="icon-filter" src="/webstatic/filebox/css/images/share.png" />收到的共享</div>' +
        '      <div class="filter-item" data-filter="company"><img class="icon-filter" src="/webstatic/filebox/css/images/company.png" />公司文件</div>' +
        '      <div class="filter-divide">筛选器</div>' +
        '      <div class="filter-item" data-filter="favorite"><img class="icon-filter" src="/webstatic/filebox/css/images/star.png" />星标文件</div>' +
        '      <div class="filter-item" data-filter="myshare"><img class="icon-filter" src="/webstatic/filebox/css/images/myshare.png" />我的共享文件夹</div>' +
        '   </div>' +
        '   <div class="doc-list-wrap"></div>' +
        '   <div class="opt-wrap">' +
        '       <div class="opt-item action-newfolder" data-action="newfolder">' +
        '           <img src="/webstatic/filebox/css/images/newfolder.png" />' +
        '           <p>新建文件夹</p>' +
        '       </div>' +
        '       <div class="opt-item action-shareto" data-action="shareto">' +
        '           <img src="/webstatic/filebox/css/images/shareto.png" />' +
        '           <p>共享</p>' +
        '       </div>' +
        '       <div class="opt-item action-share" data-action="link">' +
        '           <img src="/webstatic/filebox/css/images/link.png" />' +
        '           <p>分享</p>' +
        '       </div>' +
        '       <div class="opt-item" data-action="send">' +
        '           <img src="/webstatic/filebox/css/images/send.png" />' +
        '           <p>发送</p>' +
        '       </div>' +
        '   </div>' +
        '</div>'
    App.modules.layout = layout
})(jQuery)
